﻿using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.GridFS;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;

namespace MongoDBSample.Common.Utils
{
    public class MongoHelper<T> where T : class
    {
        public MongoCollection<T> Collection { get; private set; }

        public MongoGridFS FS { get; private set; }

        public MongoHelper()
        {
            var con = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
            var server = MongoServer.Create(con);
            var db = server.GetDatabase(con.DatabaseName);
            this.Collection = db.GetCollection<T>(typeof(T).Name.ToLower());
            this.FS = db.GridFS;
        }

        public ObjectId AddFile(Stream fileStream, string fileName)
        {
            var fileInfo = FS.Upload(fileStream, fileName);
            return (ObjectId)fileInfo.Id;
        }

        public void DeleteFile(ObjectId id)
        {
            FS.DeleteById(id);
        }

        public Stream GetFile(ObjectId id)
        {
            var file = FS.FindOneById(id);
            return file.OpenRead();
        }

    }
}